using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {
	public int Speed;
	public int Jump;
	
	private bool _onGround;
	private bool _collideLeft;
	private bool _collideRight;
	
	// Use this for initialization
	void Start () {
		Speed = 1;
		Jump = 6;
	}
	
	void OnCollisionEnter(Collision collision) {
		var down = _onGround;
		var left = _collideLeft;
		var right = _collideRight;
		
		foreach (var contact in collision.contacts) {
			var compareDown = Vector3.Angle((contact.point - transform.position).normalized, new Vector3(0, -1, 0));
			if (compareDown < 30) {
				down = true;
			}
			var compareLeft = Vector3.Angle((contact.point - transform.position).normalized, new Vector3(-1, 0, 0));
			if (compareLeft < 70) {
				left = true;
			}
			var compareRight = Vector3.Angle((contact.point - transform.position).normalized, new Vector3(1, 0, 0));
			if (compareRight < 70) {
				right = true;
			}
		}
		
		_onGround = down;
		_collideLeft = left;
		_collideRight = right;
	}
	
	void OnCollisionExit(Collision collision) {
		var down = _onGround;
		var left = _collideLeft;
		var right = _collideRight;
		
		foreach (var contact in collision.contacts) {
			var compareDown = Vector3.Angle((contact.point - transform.position).normalized, new Vector3(0, -1, 0));
			if (compareDown < 30) {
				down = false;
			}
			var compareLeft = Vector3.Angle((contact.point - transform.position).normalized, new Vector3(-1, 0, 0));
			if (compareLeft < 70) {
				left = false;
			}
			var compareRight = Vector3.Angle((contact.point - transform.position).normalized, new Vector3(1, 0, 0));
			if (compareRight < 70) {
				right = false;
			}
		}
		
		_onGround = down;
		_collideLeft = left;
		_collideRight = right;
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKey(KeyCode.A) && !_collideLeft) {
			transform.position -= new Vector3(1, 0, 0) * Speed * Time.deltaTime;
		}
		if (Input.GetKey(KeyCode.D) && !_collideRight) {
			transform.position += new Vector3(1, 0, 0) * Speed * Time.deltaTime;
		}
		if (Input.GetKeyDown(KeyCode.Space) && _onGround) {
			rigidbody.velocity += new Vector3(0, 1, 0) * Jump;
		}
	}
}
